//===----------------------------------------------------------------------===//
//
//                         BusTub
//
// index_scan_executor.cpp
//
// Identification: src/execution/index_scan_executor.cpp
//
// Copyright (c) 2015-19, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "execution/executors/index_scan_executor.h"

namespace bustub {
IndexScanExecutor::IndexScanExecutor(ExecutorContext *exec_ctx, const IndexScanPlanNode *plan)
    : AbstractExecutor(exec_ctx),
      plan_(plan),
      info_(exec_ctx->GetCatalog()->GetIndex(plan->index_oid_)),
      table_info_(exec_ctx->GetCatalog()->GetTable(info_->table_name_)),
      iter_(dynamic_cast<BPlusTreeIndexForTwoIntegerColumn *>(info_->index_.get())->GetBeginIterator()) {}

void IndexScanExecutor::Init() {}

auto IndexScanExecutor::Next(Tuple *tuple, RID *rid) -> bool {
  if (info_ != nullptr) {
    while (!iter_.IsEnd()) {
      auto rd = (*iter_).second;
      auto tp = table_info_->table_->GetTuple(rd);
      if (tp.first.is_deleted_) {
        ++iter_;
      } else {
        *tuple = tp.second;
        *rid = tuple->GetRid();
        ++iter_;
        return true;
      }
    }
  }
  return false;
}

}  // namespace bustub
